package org.reos;

import java.util.ArrayList;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * User: Alexander Rogin
 * Date: 23.12.13
 * Time: 18:13
 * To change this template use File | Settings | File Templates.
 */
public class ReLogViewer {
    public static final long APP_LAUNCH_TIME_NANO = System.nanoTime();

    private static final String EXPECTED_ARGS[] = {
            "Path to a HEX file",
            "Serial port name",
            "Timeout for reading incoming data (seconds), the app exits if no data read during this time"
    };

    public static void main(String[] args) {
        String hexFileName;
        String portName;
        int exitTimeout;
        if (args.length != EXPECTED_ARGS.length) {
            System.out.println("There is wrong number of input arguments");
            System.out.println(EXPECTED_ARGS.length + " argument(s) expected:");
            for (int i = 0; i < EXPECTED_ARGS.length; i++) {
                System.out.println("\t - " + EXPECTED_ARGS[i]);
            }
                return;
        }
        hexFileName = args[0];
        portName = args[1];
        exitTimeout = Integer.parseInt(args[2]);

        TreeMap<Integer, String> stringMap = new MemoryParser().parseHexFile(hexFileName);
        if (stringMap == null) {
            System.out.println("Could not parse the HEX file");
            return;
        } else {
            for (int key : stringMap.keySet()) {
                System.out.println(key + ": " + stringMap.get(key));
            }
        }

        ReLogPrinter logPrinter = new ReLogPrinter(stringMap);
        ReSerial serialPort = new ReSerial(portName);
        ReLogSynchronizer synchronizer = new ReLogSynchronizer();
        int cnt = 0;
        try {
            serialPort.connect();
            ArrayList<ReLogByte> data;
            long startTime = System.currentTimeMillis();
            long endTime = startTime;
            while ((endTime - startTime) / 1000 < exitTimeout) {      // measurements in seconds
                Byte b = serialPort.readByteIfAvailable();
                if (b != null) {
                    data = synchronizer.processIncomingByte(new ReLogByte(b, System.nanoTime()));
                    if (data != null) {
                        logPrinter.processData(data);
                        cnt++;
                    }
                    endTime = startTime = System.currentTimeMillis();
                } else {
                    endTime = System.currentTimeMillis();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        serialPort.closeConnection();
        System.out.println("Timeout, ReLogViewer exits, cnt=" + cnt);
    }
}
